import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/constants.dart';
import 'package:mall/core/models/me.dart';
import 'package:mall/core/providers/app_model.dart';
import 'package:mall/screens/mine/user_page.dart';
import 'package:mall/screens/mine/user_password_page.dart';
import 'package:mall/screens/mine/webview_page.dart';
import 'package:mall/components/login_button.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SettingPage extends StatelessWidget {
  static const routeName = '/SettingPage';
  final Me args;

  SettingPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('设置'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            _HeaderWidget(me: args),
            SizedBox(height: 10),
            _ListItemWidget(
              title: '修改密码',
              function: () {
                Navigator.of(context).pushNamed(UserPasswordPage.routeName);
              },
            ),
            SizedBox(height: 10),
            Container(
              color: Colors.white,
              child: Column(
                children: <Widget>[
                  _ListItemWidget(
                    title: '关于我们',
                    function: () {
                      _onAboutClicked(context);
                    },
                  ),
                  _DividerWidget(),
                  _ListItemWidget(
                    title: '用户协议',
                    function: () {
                      _onAgreementClicked(context);
                    },
                  ),
                  _DividerWidget(),
                  _ListItemWidget(
                    title: '隐私协议',
                    function: () {
                      _onPrivacyClicked(context);
                    },
                  ),
                  _DividerWidget(),
                  _ListItemWidget(
                    title: '清理缓存',
                    function: () {
                      EasyLoading.showToast('已清理');
                    },
                  ),
                  if (Platform.isAndroid) ...[
                    _DividerWidget(),
                    _ListItemWidget(
                      title: '更新版本',
                      function: () {
                        FlutterBugly.checkUpgrade();
                      },
                    ),
                  ],
                ],
              ),
            ),
            SizedBox(height: 45),
            LoginButton(
              title: '退出登录',
              function: () => _logout(context),
            ),
            Container(
              margin: EdgeInsets.all(32),
              child: FutureBuilder(
                future: _getVersion(),
                builder: (context, snapshot) {
                  String version = snapshot.hasData ? snapshot.data : '--';
                  return Column(
                    children: <Widget>[
                      Text(
                        '当前版本 $version',
                        style: TextStyle(fontSize: 18),
                      ),
                      SizedBox(
                        height: 8,
                      ),
                      Text('@copyright 微一中森（南京）生态科技有限公司')
                    ],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _onAgreementClicked(BuildContext context) async {
    AppModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed(
      WebViewPage.routeName,
      arguments: WebViewPageArgs(
        '用户协议',
        '请仔细阅读以下条款：',
        '$api_base_url/app/protocol/user?sid=${model.bindingStoreId}',
      ),
    );
  }

  void _onPrivacyClicked(BuildContext context) async {
    AppModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed(
      WebViewPage.routeName,
      arguments: WebViewPageArgs(
        '隐私协议',
        '请仔细阅读以下条款：',
        '$api_base_url/app/protocol/privacy?sid=${model.bindingStoreId}',
      ),
    );
  }

  void _onAboutClicked(BuildContext context) async {
    AppModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed(
      WebViewPage.routeName,
      arguments: WebViewPageArgs(
        '关于我们',
        '',
        '$api_base_url/app/about?sid=${model.bindingStoreId}',
      ),
    );
  }

  void _logout(BuildContext context) async {
    AppModel appModel = Provider.of(context, listen: false);
    await appModel.clear();
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.remove('accessToken');
    Navigator.of(context).pop();
  }

  Future<String> _getVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }
}

class _HeaderWidget extends StatelessWidget {
  final Me me;

  const _HeaderWidget({
    Key key,
    @required this.me,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      height: 90,
      child: Row(
        children: <Widget>[
          SizedBox(width: 12),
          CircleAvatar(
            radius: 30,
            backgroundImage: CachedNetworkImageProvider(me.avatar),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  me.nickname ?? '暂无昵称',
                  style: TextStyle(fontSize: 17),
                ),
                SizedBox(height: 8),
                Text(
                  '会员号：${me.username}',
                  style: TextStyle(fontSize: 12),
                ),
              ],
            ),
          ),
          GestureDetector(
            onTap: () => Navigator.of(context).pushNamed(UserPage.routeName, arguments: me),
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                border: Border.all(color: Theme.of(context).primaryColor),
                borderRadius: BorderRadius.all(Radius.circular(8)),
              ),
              width: 52,
              height: 24,
              child: Text(
                '编辑',
                style: TextStyle(
                  color: Theme.of(context).primaryColor,
                  fontSize: 12,
                ),
              ),
            ),
          ),
          SizedBox(width: 17)
        ],
      ),
    );
  }
}

class _DividerWidget extends StatelessWidget {
  const _DividerWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Divider(height: 1, indent: 17, color: Colors.black12);
  }
}

class _ListItemWidget extends StatelessWidget {
  final String title;
  final Function function;

  const _ListItemWidget({
    Key key,
    @required this.title,
    @required this.function,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        color: Colors.white,
        height: 45,
        child: Row(
          children: <Widget>[
            SizedBox(width: 17),
            Expanded(
              child: Text(
                title,
                style: TextStyle(color: Color(0xFF333333), fontSize: 16),
              ),
            ),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colors.black26,
            ),
            SizedBox(width: 8),
          ],
        ),
      ),
      onTap: function,
    );
  }
}
